package com.mlz.mlzmall.ui.activity.act.base;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.UserBean;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.RequestUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.ToastUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyErrorHelper;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyRequestManager;
import com.mlz.mlzmall.ui.inter.ExitActivity;
import com.mlz.mlzmall.ui.activity.act.main.MyApplication;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.ACache;
import com.mlz.mlzmall.ui.utils.util.SharedUtils;
import com.mlz.mlzmall.ui.utils.vali.PermissionsActivity;
import com.mlz.mlzmall.ui.utils.vali.PermissionsChecker;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述：所有的Activity界面都继承BaseActivity
 * Created by benny on 2016/5/7.
 * ProjectName：mlzMall.
 */
public class BaseActivity extends Activity implements OnClickListener {
    private static final String TGA = "BaseActivity";
    protected long exitTime;
    protected ExitActivity exitActivity;
    protected String tag = "";//网络请求tag标识
    protected RequestQueue requestQueue;
    protected String sessionId;//sessionId很关键的哦
    protected String sessionId2;//sessionId很关键的哦
    public ImageLoader imageLoader = ImageLoader.getInstance();
    public DisplayImageOptions options;
    protected Context mContext;

    public String telephone;
    protected int isget;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestQueue = ((MyApplication) getApplication()).getRequestQueue();

        mContext = this;
        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.mipmap.pic_22_1_icon_register_success)
                .showImageOnFail(R.mipmap.pic_22_1_icon_register_success)
                .cacheInMemory(true)
                .cacheOnDisc(true)
                .build();
        //初始化
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .memoryCacheExtraOptions(480, 480)  // 缓存在内存的图片的宽和高度
                .discCacheExtraOptions(480, 480, Bitmap.CompressFormat.PNG, 85, null)   //CompressFormat.PNG类型，70质量（0-100）
                .memoryCache(new WeakMemoryCache())
                .memoryCacheSize(2 * 1024 * 1024)   // 缓存到内存的最大数据
                .discCacheSize(50 * 1024 * 1024)    // 缓存到文件的最大数据
                .discCacheFileCount(1000)           // 文件数量
                .defaultDisplayImageOptions(options)// 上面的options对象，一些属性配置
                .build();
        imageLoader.init(config);

        sessionId = ACache.get(mContext).getAsString("sessionKeyLogin");
        telephone=ACache.get(mContext).getAsString("phoneid");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        //点击了键盘后退键
        BaseActivity.this.finish();
        BaseActivity.this.overridePendingTransition(R.anim.right_in, R.anim.right_out);

    }

    protected void showTitle() {
        showToast("程序错误");

    }

    //获取登陆成功前的session
    protected void getSessionNow() {
        executeRequest(RequestUtils.getSession(mContext, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    String data = jsonObject.getString("data");
                    JSONObject json = new JSONObject(data);
                    String sessionKey = json.getString("sessionKey");
                    Log.i(TGA, "1服务器返回的session：" + sessionKey);
//                    if (sessionId.equals("")) {
                    SharedUtils.remove(mContext, ConfigInfo.SESSIONKEY);
                    SharedUtils.put(mContext, ConfigInfo.SESSIONKEY, sessionKey);
//                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }));
    }

    protected void showToast(String str) {
        //打印Toast信息
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();

    }

    protected void executeRequest(Request<?> request) {
        request.setRetryPolicy(new DefaultRetryPolicy(10000, 0,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        VolleyRequestManager.addRequest(request, this);
    }

    protected Response.ErrorListener errorListener() {
        return new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ToastUtils.showToast(mContext, VolleyErrorHelper.getMessage(error, mContext));
            }
        };
    }

    protected String isNull(String str) {
        //判断是否空，为空返回""，不是空返回str
        if (str == null || str.length() == 0) {
            return "";
        }
        return str;
    }

    protected void exit(final Activity activity) {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            showToast(getString(R.string.exitApp));
            exitTime = System.currentTimeMillis();
        } else {
            exitActivity = ((MyApplication) activity.getApplication())
                    .getExit();
            if (exitActivity != null) {
                exitActivity.ExitApp();
            }
            activity.finish();
            System.exit(0);
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    @Override
    public void onClick(View v) {
        //事键监听处理
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //   RequestManager.cancelAll(tag);//请求界面销毁时干掉网络请求
    }

    protected void getUserData() {
        tag = "rGet";
        Map<String, String> param1 = new HashMap<String, String>();
        param1.put("telephone", isNull(MyApplication.getInstace().getLoginUser().getAccout()));

        JSONObject jsonObject = new JSONObject(param1);
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, URL.CUSTOMER.INFO, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.e(tag, jsonObject.toString());
                UserBean userBean = RequestUtils.userInfOnResponse(jsonObject.toString());//保存用户信息
                MyApplication.getmInstance().setLoginUser(userBean);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(tag, error.getMessage(), error);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };

        // 设置该请求的标签
        jsonRequest.setTag(tag);
        // 将请求添加到队列中
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);

    }

}
